//
//  BorrowApplyViewController.m
//  51易借
//
//  Created by apple on 2017/9/19.
//  Copyright © 2017年 张睿. All rights reserved.
//

#import "BorrowApplyViewController.h"
#import "BorrowApplyTableViewCell.h"
#import "BorrowApplyModel.h"
#import "MemberInfoModel.h"
#import "FMDeviceManager.h"
#import "ServiceCostView.h"
#import "ImmediatelyRepayController.h"
#import "UIWebViewController.h"

@interface BorrowApplyViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)BorrowApplyTableViewCell * cell;
@property (nonatomic,strong)BorrowApplyModel * pageModel;
@property (nonatomic,strong)MemberInfoModel * member;
@property (nonatomic, weak)UIView * backView;
@property (nonatomic, strong)ServiceCostView * serviceCostView;
//@property (nonatomic,strong)BorrowDetailModel * detailModel;
//平台服务费
@property (nonatomic,copy)NSString * platformServiceFee;
//信息认证费用
@property (nonatomic,copy)NSString * infoAuthFee;
//风控服务费
@property (nonatomic,copy)NSString * riskServiceFee;
//风控准备金
@property (nonatomic,copy)NSString * riskPrepareFee;

@property (nonatomic,copy)NSString * explationString;


//@property (nonatomic,strong)FMDeviceManager *manager;

@end

@implementation BorrowApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toShowSeviceCost) name:@"toShowSeviceCost" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToWebVCSix) name:@"pushToWebVCSix" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToWebVCSeven) name:@"pushToWebVCSeven" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToWebVCEight) name:@"pushToWebVCEight" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hiddenServiceView) name:@"hiddenView" object:nil];
    
    static FMDeviceManager_t *manager;
     manager = [FMDeviceManager sharedManager];
    
    // 准备SDK初始化参数
    NSMutableDictionary *options = [NSMutableDictionary dictionary];

    [options setValue:@"allowd" forKey:@"allowd"];  // TODO
    
    // 此处替换为您的合作方标识
    [options setValue:@"51yjk" forKey:@"partner"];
   
    manager->initWithOptions(options);
    
    
    
    [self setupNavBar];
    [self setupUI];
    [self getApplyInfo];
    [self getPageModel];
//    [self getDetailModel];
}

- (void)setupNavBar{
    [self setupForDismissKeyboard];
    self.title = @"申请借款";
    self.topView.backgroundColor = TOTAL_COLOR;
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToLastView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}
-(void)setupUI
{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = NO;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([BorrowApplyTableViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"item"];
}

- (void)backToLastView{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 610;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.cell==nil)
    {
        self.cell=[tableView dequeueReusableCellWithIdentifier:@"item" forIndexPath:indexPath];
        [self.cell setSelectionStyle:NO];
        self.tableView.backgroundColor = self.cell.backgroundColor;
        [self.cell setFeiBlock:^(BorrowApplyModel*model){
            
        }];
        [self.cell setSureBlock:^(BorrowApplyModel*model){
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"确认要申请借款吗？"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                      [self applyTask];
                                                                      //响应事件
                                                                      
                                                                  }];
            UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [alert addAction:cancelAction];
            [self presentViewController:alert animated:YES completion:nil];
        }];
        [self.cell setAgreementBlock:^(NSInteger index) {
            switch (index) {
                case 0:
                {
                    //借款协议跳转
                }
                    break;
                case 1:
                {
                    //平台服务协议跳转
                }
                    break;
                case 2:
                {
                    //授权扣款委托书
                }
                    break;
                default:
                    break;
            }
        }];
    }
    self.cell.model = self.pageModel;
    self.cell.member = self.member;
    return self.cell;
}


-(void)getApplyInfo
{
    ParaModel*para = [ParaModel new];
    
    
    [[NetworkTool shareManager] POST:[Interfacefile getPreLoanApplyInfo] Param:[para toDictionary] andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
        if([[responseObject objectForKey:@"code"]intValue]==0)
        {
            self.pageModel = [[BorrowApplyModel alloc] initWithDictionary:[responseObject objectForKey:@"data"] error:nil];
            [self.tableView reloadData];
            
            NSDictionary * data = responseObject[@"data"];
            
            self.platformServiceFee = [NSString stringWithFormat:@"%@",data[@"platformServiceFee"]];
            self.infoAuthFee = [NSString stringWithFormat:@"%@",data[@"infoAuthFee"]];
            self.riskServiceFee = [NSString stringWithFormat:@"%@",data[@"riskServiceFee"]];
            self.riskPrepareFee = [NSString stringWithFormat:@"%@",data[@"riskPrepareFee"]];
            
            float borrowAmount = [data[@"borrowAmount"] floatValue];
            float overdueRate = [data[@"overdueRate"] floatValue];
            float explation = borrowAmount * overdueRate;
            
            self.explationString = [NSString stringWithFormat:@"%.2f",explation];
        }else{
            
            [self showHint:[responseObject objectForKey:@"message"]];
            
            
        }
    } andFailure:^(NSError * _Nonnull error) {
        [self showHint:@"网络错误"];
    }];
    
}


-(void)applyTask
{
    
    if(self.cell.agreeBtn.selected == NO)
    {
        [self showHint:@"请先阅读并同意协议"];
        return;
    }
    
    NSString * longitude = DEF_GET_OBJECT(@"longitude");
    NSString * latitude = DEF_GET_OBJECT(@"latitude");
    
    if (longitude || latitude) {
        
        NSDictionary * para = @{@"longitude":longitude,@"latitude":latitude};
        
        [[NetworkTool shareManager] POST:@"user/uploadUserLocation.json" parameters:para progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            NSLog(@"==%@",error);
            
        }];
    }
    
    
    
//    ParaModel*para = [ParaModel new];
//    [para toDictionary]
    // 获取设备管理器实例
    FMDeviceManager_t *manager = [FMDeviceManager sharedManager];
    
    // 准备SDK初始化参数
//    NSMutableDictionary *options = [NSMutableDictionary dictionary];
//    
//    /*
//     * SDK具有防调试功能，当使用xcode运行时(开发测试阶段),请取消下面代码注释，
//     * 开启调试模式,否则使用xcode运行会闪退。上架打包的时候需要删除或者注释掉这
//     * 行代码,如果检测到调试行为就会触发crash,起到对APP的保护作用
//     */
//    // 上线Appstore的版本，请记得删除此行，否则将失去防调试防护功能！
//    [options setValue:@"allowd" forKey:@"allowd"];  // TODO
//    
//    // 指定对接同盾的测试环境，正式上线时，请删除或者注释掉此行代码，切换到同盾生产环境
//    //                 [options setValue:@"sandbox" forKey:@"env"]; // TODO
//    
//    // 此处替换为您的合作方标识
//    [options setValue:@"51yjk" forKey:@"partner"];
////    [options setValue:@"6d5e787637774868a2c3778a60c0961a" forKey:@"partner"];
//    
//    
//    // 使用上述参数进行SDK初始化
//    manager->initWithOptions(options);
    
    /*
     * 获取设备指纹黑盒数据，请确保在应用开启时已经对SDK进行初始化，切勿在get的时候才初始化
     * 如果此处获取到的blackBox特别长(超过400字节)，说明初始化尚未完成(一般需要1-3秒)，或者由于网络问题导致初始化失败，进入了降级处理
     * 降级不影响正常设备信息的获取，只是会造成blackBox字段超长，且无法获取设备真实IP
     * 降级数据平均长度在2KB以内,一般不超过3KB,数据的长度取决于采集到的设备信息的长度,无法100%确定最大长度
     */
    NSString *blackBox = manager->getDeviceInfo();
//    NSLog(@"同盾设备指纹数据: %@", blackBox);
    // 将blackBox随业务请求提交到您的服务端，服务端调用同盾风险决策API时需要带上这个参数
    
    NSDictionary * parameters = @{@"blackBox":blackBox,@"clientType":@"2"};


    
    [[NetworkTool shareManager] POST:[Interfacefile submitLoanApply] Param:parameters andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
        if([[responseObject objectForKey:@"code"]intValue]==0)
        {
//            [self showHint:@"已申请"];
//            [self.navigationController popViewControllerAnimated:YES];
            NSString * data = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"data"]];
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"申请成功"
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      //响应事件
//                                                                      [self.navigationController popViewControllerAnimated:YES];
                                                                      
                                                                      ImmediatelyRepayController * vc = [ImmediatelyRepayController new];
                                                                      //    vc.hidesBottomBarWhenPushed = YES;
                                                                      HIDDEN_TAB;
                                                                      vc.loanID = data;
                                                                      if ([self.from isEqualToString:@"home"]) {
                                                                         vc.borrow = @"3";
                                                                      }else if([self.from isEqualToString:@"Repay"]){
                                                                         vc.borrow = @"4"; 
                                                                      }
                                                                      
                                                                      [self.navigationController pushViewController:vc animated:YES];
                                                                      
                                                                      SHOW_TAB;
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            [self showHint:[responseObject objectForKey:@"message"]];
            
            
        }
    } andFailure:^(NSError * _Nonnull error) {
        [self showHint:@"网络错误"];
    }];
    
}


-(void)getPageModel
{
    ParaModel*para = [ParaModel new];
    
    
    [[NetworkTool shareManager] POST:[Interfacefile loadCurrentPersonalInfo] Param:[para toDictionary] andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
        if([[responseObject objectForKey:@"code"]intValue]==0)
        {
            self.member = [[MemberInfoModel alloc] initWithDictionary:[responseObject objectForKey:@"data"] error:nil];
            [self.tableView reloadData];
            
        }else{
            
            [self showHint:[responseObject objectForKey:@"message"]];
            
            
        }
    } andFailure:^(NSError * _Nonnull error) {
        [self showHint:@"网络错误"];
    }];
    
}

- (void)toShowSeviceCost{
    
    UIView * backView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    backView.backgroundColor = [UIColor blackColor];
    backView.alpha = 0.55;
    self.backView = backView;
    
    [self.navigationController.view addSubview:self.backView];
    
    self.serviceCostView = [[ServiceCostView alloc] initWithFrame:CGRectMake(40 * SCREENH6, 205 * SCREENH6, 302 * SCREENH6, 275 * SCREENH6)];
    
    self.serviceCostView.platformServiceFee = self.platformServiceFee;
    self.serviceCostView.infoAuthFee = self.infoAuthFee;
    self.serviceCostView.riskServiceFee = self.riskServiceFee;
    self.serviceCostView.riskPrepareFee = self.riskPrepareFee;
    self.serviceCostView.explationString = self.explationString;
    
    [self.navigationController.view addSubview:self.serviceCostView];
    
    //下面这段代码是 将bottomView调整到父视图的最上面
    [self.view bringSubviewToFront:self.serviceCostView];
}

- (void)pushToWebVCSix{
    
    HIDDEN_TAB;
    
    UIWebViewController * webVC = [UIWebViewController new];
    
    webVC.count = @"6";
    
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)pushToWebVCSeven{
    
    HIDDEN_TAB;
    
    UIWebViewController * webVC = [UIWebViewController new];
    
    webVC.count = @"7";
    
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)pushToWebVCEight{
    
    HIDDEN_TAB;
    
    UIWebViewController * webVC = [UIWebViewController new];
    
    webVC.count = @"8";
    
    [self.navigationController pushViewController:webVC animated:YES];
}

- (void)hiddenServiceView{
    
    [self.backView removeFromSuperview];
    [self.serviceCostView removeFromSuperview];
}

@end
